//
//  ViewController.m
//  糗事百科－AFNetworking
//
//  Created by apple on 15/9/2.
//  Copyright (c) 2015年 戴维营. All rights reserved.
//

#import "ViewController.h"
#import "TFHpple.h"
#import "AFNetworking.h"
#import "UIKit+AFNetworking.h"
#import "Story.h"

@interface ViewController ()


{
    NSInteger _currentIndex;
    
    NSString *_filePath;
    NSMutableArray *_array;
    
    __weak IBOutlet UIImageView *personImageView;
    __weak IBOutlet UITextView *contentTextView;

    __weak IBOutlet UILabel *commentLabel;
    __weak IBOutlet UILabel *votesLabel;
    
    __weak IBOutlet UILabel *personNameLabel;
}


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    _filePath = @"http://www.qiushibaike.com/text";
    _array = [NSMutableArray array];
    
    
    [self loadStoryFromQiuBai];
    
    
    
    
    // Do any additional setup after loading the view, typically from a nib.
}

//上一个；
- (IBAction)preButtonClicked:(UIButton *)sender
{
    if ([_array count] > 0)
    {
        _currentIndex--;
        if (_currentIndex < 0)
        {
            _currentIndex = [_array count] - 1;
        }
    }
    [self displayWithStory:_array[_currentIndex]];
    
}

//下一个；
- (IBAction)nextButtonClicked:(UIButton *)sender
{
    if ([_array count] > 0)
    {
        _currentIndex++;
        if (_currentIndex >= [_array count])
        {
            _currentIndex = 0;
        }
    }
    [self displayWithStory:_array[_currentIndex]];
    NSLog(@"%@",_array[_currentIndex]);
}



- (void)loadStoryFromQiuBai
{
//    先创建一个HTTP请求管理器；
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
//    由于默认的管理器中对http响应的序列化器属性是AFJSONResponseSerializer;
    
//    我们现在是要取html数据，因此设置为普通的AFHTTPResponseSerializer,不然跑到失败里面去了；
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_filePath]];
    
    //修改HTTP请求头域，伪装成PC浏览器；
    
    [req setValue:@"Mozilla/5.0" forHTTPHeaderField:@"User-Agent"];
    
//   创建一个请求操作；
    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:req success:^void(AFHTTPRequestOperation *operation, id responseObject){
        
//        交给解析HTML的方法处理；
        
        [self parseHTMLData:responseObject];
    } failure:^void(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败：%@",error);
    }];
    
    [operation start];//开始请求

}


//解析网页
- (void)parseHTMLData:(NSData *)data
{
//    [data writeToFile:@"Users/apple/Desktop/糗事.html" atomically:YES];
    data = [NSData dataWithContentsOfFile:@"Users/apple/Desktop/糗事.html"];
    
//    解析html
    TFHpple *doc = [[TFHpple alloc] initWithHTMLData:[NSData dataWithContentsOfFile:@"Users/apple/Desktop/糗事.html"]];
    
    NSArray *result = [doc searchWithXPathQuery:@"//div[@class='article block untagged mb15']"];//取出所有故事一页20条；
    
    for (TFHppleElement *ele in result)
    {
        TFHppleElement *perImager = [[ele searchWithXPathQuery:@"//div[@class='author']/a/img"] firstObject];//用户头像地址，
        NSString *personImager = [perImager attributes][@"src"];
        
        TFHppleElement *conEle = [[ele searchWithXPathQuery:@"//div[@class= 'content']"] firstObject];//内容；
        NSString * cont= [conEle content];
        NSString *content = [cont stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


        TFHppleElement *voteEle = [[ele searchWithXPathQuery:@"//div[@class='stats']/span/i"] firstObject];//票数；
        NSString *vote = [voteEle content];
        
        TFHppleElement *comEle = [[ele searchWithXPathQuery:@"//div[@class= 'stats']/span/a/i"] firstObject];//评论数；
        NSString *comment = [comEle content];
        
        TFHppleElement *perEle = [[ele searchWithXPathQuery:@"//div[@class='author']/a"] firstObject];//昵称
        NSString *perN = [perEle content];
        NSString *perName = [perN stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        Story *story = [Story new];
        story.personName = perName;
        story.voteStr = vote;
        story.contentStr = content;
        story.commentStr = comment;
        story.personImagePath =personImager;
        
    
        [_array addObject:story];
        
        
        
    }
    [self displayWithStory:_array[0]];
}
- (void)displayWithStory:(Story *)story
{
    contentTextView.text = story.contentStr;
    personNameLabel.text = story.personName;

    //---------------------------------------
    
    NSLog(@"%@",story.personName);
    
    votesLabel.text = [NSString stringWithFormat:@"%@ 好笑",story.voteStr];
    commentLabel.text = [NSString stringWithFormat:@"%@ 评论",story.commentStr];
    
//    ------------------------------------
    NSLog(@"%@",personNameLabel.text);
    
//    重点，AFN给imageview加的类别的方法
    
    [personImageView setImageWithURL:[NSURL URLWithString:story.personImagePath]];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
